package com.example.administrator.hero;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.administrator.hero.fragments.LiveFragment;
import com.example.administrator.hero.fragments.RideoFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private FrameLayout frame;
    private RadioGroup rg;
    private RadioButton video;
    private RadioButton live;
    private List<Fragment> fragments;
    private int nowIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        fragments = new ArrayList<>();
        intView();
        initData();
        iniListener();
        getSupportFragmentManager().beginTransaction().add(R.id.frame,fragments.get(0)).commit();
    }

    private void initData() {
        fragments.add(new RideoFragment());
        fragments.add(new LiveFragment());
    }

    private void iniListener() {
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId ){
                    case R.id.bt_video:
                        swichFragment(0);
                        break;
                    case R.id.bt_live:
                        swichFragment(1);
                        break;
                }
            }
        });
    }
    public void swichFragment(int targetIndex){
        Fragment targetfragment = fragments.get(targetIndex);
        Fragment nowfragment = fragments.get(nowIndex);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(targetfragment.isAdded()){
            transaction.hide(nowfragment).show(targetfragment);
        }else{
            transaction.hide(nowfragment).add(R.id.frame,targetfragment);
        }
        transaction.commit();
        nowIndex=targetIndex;
    }

    private void intView() {
        frame = (FrameLayout) findViewById(R.id.frame);
        rg = (RadioGroup) findViewById(R.id.rg);
        video = (RadioButton) findViewById(R.id.bt_video);
        live = (RadioButton) findViewById(R.id.bt_live);
    }
}
